<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="订单编号" prop="id">
              <el-input v-model="queryParams.id" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="联系人" prop="contacts">
              <el-input v-model="queryParams.contacts" placeholder="请输入联系人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactsPhone">
              <el-input v-model="queryParams.contactsPhone" placeholder="请输入联系电话" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="下单时间">
              <el-date-picker clearable v-model="orderTime" value-format="YYYY-MM-DD"
                placeholder="请选择下单时间" type="datetimerange"
                start-placeholder="开始时间"  end-placeholder="结束时间"/>
            </el-form-item>
            <el-form-item label="服务地点" prop="graveName">
              <el-input v-model="queryParams.graveName" placeholder="请输入服务地点" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="订单状态" prop="orderStatus">
              <el-select v-model="queryParams.orderStatus" placeholder="请选择状态" clearable>
                <el-option label="待服务" value="1" />
                <el-option label="服务中" value="2" />
                <el-option label="已完成" value="3" />
                <el-option label="已退款" value="4" />
                <el-option label="退款中" value="5" />
                <el-option label="退款失败" value="6" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-table v-loading="loading" border :data="orderList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="订单id" align="center" prop="id" v-if="true" /> -->
      <el-table-column label="序号" type="index" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="id" />
      <el-table-column label="联系人" align="center" prop="contacts" />
      <el-table-column label="联系电话" align="center" prop="contactsPhone" />
      <el-table-column label="下单时间" align="center" prop="orderTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下单次数" align="center" prop="orderCount" />
      <el-table-column label="订购套餐" align="center" prop="offerlibationVo">
        <template #default="scope">
          {{scope.row.offerlibationVo.name}}
        </template>
      </el-table-column>
      <el-table-column label="服务地点" align="center" prop="graveVo" >
        <template #default="scope">
          {{scope.row.graveVo?scope.row.graveVo.name:''}}
        </template>
      </el-table-column>
      <el-table-column label="预定时间" align="center" prop="appointmentDate">
        <template #default="scope">
          <span>{{ parseTime(scope.row.appointmentDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实付金额" align="center" prop="amount">
        <template #default="scope">
          {{scope.row.offerlibationVo.amount}}
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template #default="scope">
          <span v-if="scope.row.orderStatus == 1">待服务</span>
          <span v-else-if="scope.row.orderStatus == 2">服务中</span>
          <span v-else-if="scope.row.orderStatus == 3">已完成</span>
          <span v-else-if="scope.row.orderStatus == 4">已退款</span>
          <span v-else-if="scope.row.orderStatus == 5">退款中</span>
          <span v-else-if="scope.row.orderStatus == 6">退款失败</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="开票状态" align="center" prop="billingStatus">
        <template #default="scope">
          <span v-if="scope.row.billingStatus == 0">未开票</span>
          <span v-else-if="scope.row.billingStatus == 1">已开票</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120px">
        <template #default="scope">
          <el-tooltip content="查看" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleDetail(scope.row)"
              v-hasPermi="['cemetery:order:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="完成订单" placement="top" v-if="scope.row.orderStatus==2">
            <el-button link type="primary" icon="Check" @click="handleUpdate(scope.row,'完成订单',3)"
              v-hasPermi="['cemetery:order:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="退款" placement="top" v-if="scope.row.orderStatus==2">
            <el-button link type="primary" icon="Close" @click="handleUpdate(scope.row,'退款',4)"
              v-hasPermi="['cemetery:order:edit']"></el-button>
          </el-tooltip>
          <!-- <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['cemetery:order:remove']"></el-button>
          </el-tooltip> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="780px" append-to-body>
      <el-form ref="orderFormRef" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="服务人员" prop="serviceStaff">
              <el-input v-model="form.serviceStaff" placeholder="请输入服务人员" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.orderStatus == 3">
          <el-col :span="12">
            <el-form-item label="服务时间" prop="serviceTime">
              <el-date-picker clearable v-model="form.serviceTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择服务时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否联系客户" prop="isRelation">
              <el-radio-group v-model="form.isRelation">
                <el-radio :value="1">是</el-radio>
                <el-radio :value="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="联系记录" prop="relationRecord">
              <imageUpload v-model="form.relationRecord" @getModelUrl="getImgUrl($event,'relationRecord')" :limit="3" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务实录" prop="serviceRecord">
              <imageUpload v-model="form.serviceRecord" @getModelUrl="getImgUrl($event,'serviceRecord')" :limit="3" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务说明" prop="serviceContext">
              <el-input v-model="form.serviceContext" type="textarea" placeholder="请输入说明" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.orderStatus == 4">
          <el-col :span="24">
            <el-form-item label="退款原因" prop="refundReason">
              <el-input type="textarea" v-model="form.refundReason" placeholder="请输入退款原因" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog :title="detailDialog.title" v-model="detailDialog.visible" width="1200px" append-to-body>
      <el-form ref="orderFormRef" :model="form"  label-width="100px" disabled>
        <h3>订单信息</h3>
        <el-row>
          <el-col :span="8">
            <el-form-item label="订单编号" prop="id">
              <el-input v-model="form.id" placeholder="请输入订单编号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="下单时间" prop="orderTime">
              <el-input v-model="form.orderTime" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预定日期" prop="appointmentDate">
              <el-input v-model="form.appointmentDate"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人" prop="contacts">
              <el-input v-model="form.contacts" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="contactsPhone">
              <el-input v-model="form.contactsPhone" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="逝者姓名">
              <el-input :value="deadPersonVo?deadPersonVo.name:''" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="墓地位置">
              <el-input :value="graveVo?graveVo.name:''" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" />
            </el-form-item>
          </el-col>
        </el-row>
        <h3 v-if="form.orderStatus==3">支付信息</h3>
        <el-row v-if="form.orderStatus==3">
          <el-col :span="12">
            <el-form-item label="支付编号" prop="transactionId">
              <el-input v-model="form.transactionId" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="支付方式" prop="remark">
              <el-input value="微信支付" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="实付金额" prop="remark">
              <el-input v-model="offerlibationVo.amount">
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <h3 v-if="form.orderStatus==4||form.orderStatus==5||form.orderStatus==6">退款信息</h3>
        <el-row v-if="form.orderStatus==4||form.orderStatus==5||form.orderStatus==6">
          <el-col :span="8" v-if="form.orderStatus==4">
            <el-form-item label="退款状态" prop="transactionId">
              <el-input value="退款成功" />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.orderStatus==5">
            <el-form-item label="退款状态" prop="transactionId">
              <el-input value="退款中" />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.orderStatus==6">
            <el-form-item label="退款状态" prop="transactionId">
              <el-input value="退款失败" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作人员" prop="serviceStaff">
              <el-input  v-model="form.serviceStaff" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="提交时间" prop="orderTime">
              <el-input v-model="form.orderTime"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="退款原因" prop="refundReason">
              <el-input type="textarea" v-model="form.refundReason"/>
            </el-form-item>
          </el-col>
        </el-row>
        <h3>商品信息</h3>
        <el-row>
          <el-col :span="16">
            <el-form-item label="套餐名称" prop="name">
              <el-input v-model="offerlibationVo.name" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="套餐金额" prop="amount">
              <el-input v-model="offerlibationVo.amount">
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="套餐内容" prop="content">
              <div v-html="offerlibationVo.content"></div>
            </el-form-item>
          </el-col>
        </el-row>
        <h3 v-if="form.orderStatus==3">支付信息</h3>
        <el-row v-if="form.orderStatus==3">
          <el-col :span="8">
            <el-form-item label="服务人员" prop="serviceStaff">
              <el-input v-model="form.serviceStaff" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="服务时间" prop="serviceTime">
              <el-input v-model="form.serviceTime" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否联系客户" prop="isRelation">
              <el-input :value="form.isRelation==1?'是':'否'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系记录" prop="relationRecord">
              <imageUpload v-model="form.relationRecord" @getModelUrl="getImgUrl" :limit="3"
               :isShowTip="false"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务实录" prop="serviceRecord">
              <imageUpload v-model="form.serviceRecord" @getModelUrl="getImgUrl" :limit="3"
              :isShowTip="false"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务内容" prop="serviceContext">
              <el-input v-model="form.serviceContext" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="Order" lang="ts">
  import { detaiListOrder, getOrder, delOrder, addOrder, updateOrder } from '@/api/cemetery/order';
  import { OrderVO, OrderQuery, OrderForm } from '@/api/cemetery/order/types';

  const { proxy } = getCurrentInstance() as ComponentInternalInstance;

  const orderList = ref<OrderVO[]>([]);
  const buttonLoading = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref<Array<string | number>>([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);

  const queryFormRef = ref<ElFormInstance>();
  const orderFormRef = ref<ElFormInstance>();

  const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
  });

  const detailDialog = reactive<DialogOption>({
    visible: false,
    title: ''
  });

  const orderTime = ref('')

  const initFormData : OrderForm = {
    id: undefined,
    memberId: undefined,
    offerlibationId: undefined,
    orderTime: undefined,
    deadPersonId: undefined,
    graveId: undefined,
    contacts: undefined,
    contactsPhone: undefined,
    appointmentDate: undefined,
    remark: undefined,
    orderStatus: undefined,
    billingStatus: undefined,
    refundReason: undefined,
    serviceStaff: undefined,
    serviceTime: undefined,
    isRelation: undefined,
    relationRecord: undefined,
    serviceRecord: undefined,
    relationRecordUrl: undefined,
    serviceRecordUrl: undefined,
    serviceContext: undefined,
  }
  const data = reactive<PageData<OrderForm, OrderQuery>>({
    form: { ...initFormData },
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      memberId: undefined,
      offerlibationId: undefined,
      orderTime: undefined,
      deadPersonId: undefined,
      graveId: undefined,
      contacts: undefined,
      contactsPhone: undefined,
      appointmentDate: undefined,
      orderStatus: undefined,
      billingStatus: undefined,
      refundReason: undefined,
      serviceStaff: undefined,
      serviceTime: undefined,
      isRelation: undefined,
      relationRecord: undefined,
      serviceRecord: undefined,
      serviceContext: undefined,
      beginTime:undefined,
      endTime: undefined,
      params: {
      }
    },
    rules: {
      memberId: [
        { required: true, message: "用户id不能为空", trigger: "blur" }
      ],
      offerlibationId: [
        { required: true, message: "祭扫套餐id不能为空", trigger: "blur" }
      ],
      orderTime: [
        { required: true, message: "下单时间不能为空", trigger: "blur" }
      ],
      deadPersonId: [
        { required: true, message: "逝者id不能为空", trigger: "blur" }
      ],
      graveId: [
        { required: true, message: "墓穴id不能为空", trigger: "blur" }
      ],
      contacts: [
        { required: true, message: "联系人不能为空", trigger: "blur" }
      ],
      contactsPhone: [
        { required: true, message: "联系电话不能为空", trigger: "blur" }
      ],
      appointmentDate: [
        { required: true, message: "预约日期不能为空", trigger: "blur" }
      ],
      remark: [
        { required: true, message: "备注不能为空", trigger: "blur" }
      ],
      orderStatus: [
        { required: true, message: "订单状态 1：待服务 2：服务中 3：已完成 4：已退款不能为空", trigger: "change" }
      ],
      billingStatus: [
        { required: true, message: "开票状态 0：未开票 1：已开票不能为空", trigger: "change" }
      ],
      refundReason: [
        { required: true, message: "退款原因不能为空", trigger: "blur" }
      ],
      serviceStaff: [
        { required: true, message: "服务人员不能为空", trigger: "blur" }
      ],
      serviceTime: [
        { required: true, message: "服务时间不能为空", trigger: "blur" }
      ],
      isRelation: [
        { required: true, message: "是否联系用户 1:是 0:否不能为空", trigger: "blur" }
      ],
      relationRecord: [
        { required: true, message: "联系记录不能为空", trigger: "blur" }
      ],
      serviceRecord: [
        { required: true, message: "服务实录不能为空", trigger: "blur" }
      ],
      serviceContext: [
        { required: true, message: "服务内容不能为空", trigger: "blur" }
      ],
    }
  });

  const { queryParams, form, rules } = toRefs(data);
  const deadPersonVo = ref(null)
  const graveVo = ref(null)
  const offerlibationVo = ref(null)

  /** 查询订单列表 */
  const getList = async () => {
    loading.value = true;
    if( orderTime.value ){
      queryParams.value.beginTime = orderTime.value[0]
      queryParams.value.endTime = orderTime.value[1]
    }else{
      queryParams.value.beginTime = undefined
      queryParams.value.endTime = undefined
    }
    const res = await detaiListOrder(queryParams.value);
    orderList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  }

  /** 取消按钮 */
  const cancel = () => {
    reset();
    dialog.visible = false;
  }

  /** 表单重置 */
  const reset = () => {
    form.value = { ...initFormData };
    orderFormRef.value?.resetFields();
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
  }

  /** 多选框选中数据 */
  const handleSelectionChange = (selection : OrderVO[]) => {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = "添加订单";
  }

  /** 修改按钮操作 */
  const handleUpdate = async (row ?: OrderVO, title, orderStatus) => {
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getOrder(_id);
    Object.assign(form.value, res.data);
    form.value.orderStatus = orderStatus
    dialog.visible = true;
    dialog.title = title;
  }

  const handleDetail = async (row : any) => {
    const _id = row.id
    const res = await getOrder(_id);
    Object.assign(form.value, res.data);
    deadPersonVo.value = res.data.deadPersonVo
    graveVo.value = res.data.graveVo
    offerlibationVo.value = res.data.offerlibationVo
    detailDialog.visible = true;
    detailDialog.title = '详情';
  }

  const getImgUrl = (val : any, type : any) => {
    console.log(val, type)
    if (type == 'relationRecord') {
      form.value.relationRecordUrl = val
    } else if (type == 'serviceRecord') {
      form.value.serviceRecordUrl = val
    }
  }

  /** 提交按钮 */
  const submitForm = () => {
    orderFormRef.value?.validate(async (valid : boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (form.value.id) {
          await updateOrder(form.value).finally(() => buttonLoading.value = false);
        } else {
          await addOrder(form.value).finally(() => buttonLoading.value = false);
        }
        proxy?.$modal.msgSuccess("操作成功");
        dialog.visible = false;
        await getList();
      }
    });
  }

  /** 删除按钮操作 */
  const handleDelete = async (row ?: OrderVO) => {
    const _ids = row?.id || ids.value;
    await proxy?.$modal.confirm('是否确认删除订单编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
    await delOrder(_ids);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  }

  /** 导出按钮操作 */
  const handleExport = () => {
    proxy?.download('cemetery/order/export', {
      ...queryParams.value
    }, `order_${new Date().getTime()}.xlsx`)
  }

  onMounted(() => {
    getList();
  });
</script>
